package com.heima.web;

import com.heima.UserService.Login.Lservice;
import com.heima.pojo.User;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.net.URLEncoder;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println("username="+username+" password="+password);
        String remember = request.getParameter("remember");
        Lservice service = new Lservice();
        User user = service.getUser(username, password);
        response.setContentType("text/html;charset=utf-8");


        if (user != null){
            if (remember!=null){
                String username1 = URLEncoder.encode(username, "utf-8");
                String password1 = URLEncoder.encode(password, "utf-8");

                Cookie username2 = new Cookie("username", username1);
                Cookie password2 = new Cookie("password", password1);

                username2.setMaxAge( 60 * 60 * 24 * 7);
                password2.setMaxAge( 60 * 60 * 24 * 7);

                response.addCookie(username2);
                response.addCookie(password2);
            }
            //response.getWriter().write("登陆成功");
            HttpSession session = request.getSession();
            session.setAttribute("user",user);

            String contextPath = request.getContextPath();
            response.sendRedirect("index.jsp");
            System.out.println("登陆成功");
        }else {
            request.setAttribute("err_msg","用户名或密码不正确");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
            System.out.println("登陆失败");
        }
    }
}
